//
// Created on 2024/7/31.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be
// found, please include "napi/native_api.h".

#include "NativeEntry.h"
#include "src/ArkUIListItemNode.h"
#include "src/ArkUIListNode.h"
#include "src/ArkUITextNode.h"
#include "src/TLangList.h"
#include "src/TLangListItem.h"
#include "src/TLangText.h"
#include "tlang/tvm/TVM.h"
#include <arkui/native_node_napi.h>
#include <js_native_api.h>

namespace NativeModule {

constexpr int ARG_CNT = 5;
constexpr int BUF_SIZE = 10240;

napi_value CreateNativeRoot(napi_env env, napi_callback_info info) {
    size_t argc = ARG_CNT;
    napi_value args[ARG_CNT] = {nullptr};

    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    ArkUI_NodeContentHandle contentHandle;
    OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &contentHandle);
    NativeEntry::GetInstance()->SetContentHandle(contentHandle);

    Runtime::TVM tvm;
    auto nativeMethodTable = tvm.getClassTable()->getNativeMethodTable();
    TextWrapper::bind(nativeMethodTable);
    ListItemWrapper::bind(nativeMethodTable);
    ListWrapper::bind(nativeMethodTable);

    char *buf = new char[BUF_SIZE];
    size_t len = 0;
    for (int i = 1; i < ARG_CNT; ++i) {
        napi_get_value_string_latin1(env, args[i], buf, BUF_SIZE, &len);
        std::string code = std::string{buf};
        auto sourceFile = std::make_shared<SourceFile>("code.tl");
        sourceFile->addLine(code);
        tvm.interpretClass(sourceFile);
    }

    //     auto rootNode = CreateRootNode(std::vector<std::string>{classDecl, codeForRender});
    //     NativeEntry::GetInstance()->SetRootNode(rootNode);
    return nullptr;
}

napi_value DestroyNativeRoot(napi_env env, napi_callback_info info) {
    NativeEntry::GetInstance()->DisposeRootNode();
    return nullptr;
}

std::shared_ptr<ArkUIBaseNode> CreateRootNode(std::vector<std::string> code) {
    auto list = std::make_shared<ArkUIListNode>();
    list->SetPercentWidth(1);
    list->SetPercentHeight(1);
    for (int i = 0; i < 30; i++) {
        auto textNode = std::make_shared<ArkUITextNode>();
        textNode->SetTextContent(std::to_string(i));
        textNode->SetFontSize(30);
        textNode->SetPercentWidth(1);
        textNode->SetHeight(50);
        textNode->SetTextAlign(ARKUI_TEXT_ALIGNMENT_CENTER);
        textNode->SetBackgroundColor(0xFFfffacd);

        auto listItem = std::make_shared<ArkUIListItemNode>();
        listItem->AddChild(textNode);

        list->AddChild(listItem);
    }
    return list;
}

} // namespace NativeModule